import base64
import concurrent.futures
import json
import sys
import time

import pymysql


def fetch_data(sql):
    """查询传递过来的sql

    Args:
        sql (string): sql 语句

    Returns:
        list: 数据集
    """
    conn = pymysql.connect(
        host="43.156.247.50",  # 替换为实际的主机名
        user="root",  # 替换为实际的用户名
        password="520777",  # 替换为实际的密码
        database="house"  # 替换为实际的数据库名
    )
    cursor = conn.cursor()
    cursor.execute(sql)
    data = cursor.fetchall()
    cursor.close()
    conn.close()
    return data


def update_data(batch_id, row):
    """更新数据

    Args:
        batch_id (string): 批次id
        row (Object): 房源信息
    """
    try:
        house_id = row[0]
        conn = pymysql.connect(
            host="43.156.247.50",  # 替换为实际的主机名
            user="root",  # 替换为实际的用户名
            password="520777",  # 替换为实际的密码
            database="house"  # 替换为实际的数据库名
        )
        cursor = conn.cursor()

        try:
            # 构建插入数据的 SQL 查询
            sql = "INSERT INTO batch_house_owner (batch_id, house_id) VALUE (%s, %s);"
            values = (
                batch_id,
                house_id
            )

            # 执行 SQL 查询
            cursor.execute(sql, values)
            conn.commit()
        except Exception as e:
            print("发生异常:", str(e))

        cursor.close()
        conn.close()
    except Exception as e:
        print(f"未知异常:", str(e))


def select_house(batch_id):
    """查询全量数据并打印

    Args:
        batch_id (string): 批次id

    Returns:
        Object: 房源信息
    """
    sql = f"select	house_id ,	`section` as 小区,	CONCAT(block_no, '栋', unit_no, '单元', cell, '室') as 房号,	price as 总价,	unit_price as 单价,	area as 建筑面积,	CONCAT(room , '室', hall, '厅') as 房间,	floor as 楼层,	total_floor as 总楼层,	decoration as 装修 from	house where	house_id in (	select		house_id	from		batch_house_owner	where		batch_id = {batch_id});"
    print("查询sql:", sql)
    conn = pymysql.connect(
        host="43.156.247.50",  # 替换为实际的主机名
        user="root",  # 替换为实际的用户名
        password="520777",  # 替换为实际的密码
        database="house"  # 替换为实际的数据库名
    )
    cursor = conn.cursor()
    cursor.execute(sql)
    data = cursor.fetchall()
    cursor.close()
    conn.close()
    return data


# 获取命令行参数
# sys.argv[0] 是脚本的名称
# sys.argv[1] 是第一个参数，sys.argv[2] 是第二个参数，依此类推
if len(sys.argv) >= 3:
    arg1 = sys.argv[1]
    arg2 = sys.argv[2]
    # 解码 Base64 数据并转换为字符串
    arg2 = base64.b64decode(arg2).decode('utf-8')
    
    # 在这里可以对接收到的参数进行处理
    print("Argument 1:", arg1)
    print("Argument 2:", arg2)

    data = fetch_data(arg2)
    batch_id = int(time.time())
    with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
        futures = [executor.submit(update_data, batch_id, row) for row in data]
        concurrent.futures.wait(futures)

    print(f"执行完成: batch_id=", batch_id)

    houses = select_house(batch_id)
    if len(houses) > 0:
        for house in houses:
            print(house)
else:
    print("Insufficient number of arguments provided.", sys.argv)
